<template>
  <HeaderTitle title="实时存货报表"></HeaderTitle>
  <div class="realtimeStockPage">
    <div class="detailsBox">
      <div class="row items-center">
        <div class="col-auto dbTitle">明细</div>
        <div class="col dbTitle"><hr class="titleHR" /></div>
        <div class="col-auto exportBtnBox">
          <q-btn
            color="blue-10"
            class="exportBtn"
            label="导出"
            @click="exportTable()"
          >
            <q-icon name="fa-solid fa-file-arrow-down" class="exportSVG" />
          </q-btn>
        </div>
      </div>
      <div class="row detailTbBox">
        <q-table
          flat
          bordered
          dense
          separator="cell"
          table-header-class="bg-deep-purple-2"
          :rows="dtrows"
          :columns="dtcolumns"
          row-key="NO"
          class="detailTable"
        >
          <template v-slot:body-cell-serialNo="props">
            <q-td :props="props">
              {{ props.rowIndex + 1 }}
            </q-td>
          </template>
        </q-table>
      </div>
    </div>
    <div class="summaryBox">
      <div class="row items-center">
        <div class="col-auto sbTitle">汇总</div>
        <div class="col dbTitle"><hr class="titleHR" /></div>
        <div class="col-auto exportBtnBox">
          <q-btn
            color="blue-10"
            class="exportBtn"
            label="导出"
            @click="exportToCSV()"
          >
            <q-icon name="fa-solid fa-file-arrow-down" class="exportSVG" />
            <!-- genCsv -->
          </q-btn>
        </div>
      </div>
      <div class="row summaryTbBox">
        <table class="my-table col-12">
          <thead>
            <tr class="bg-deep-purple-2 my-table-header">
              <th>检测员身份</th>
              <th>检测员姓名</th>
              <th>部门名称</th>
              <th>工人姓名</th>
              <th>单数</th>
              <th>件数</th>
            </tr>
          </thead>
          <tbody>
            <template v-for="(item, index) in TableTotalData" :key="index">
              <tr v-for="(child, childIndex) in item.children" :key="childIndex">
                <td v-if="childIndex === 0" :rowspan="item.children.length">{{ item.role_chinese_name }}</td>
                <td v-if="childIndex === 0" :rowspan="item.children.length">{{ item.cnName }}</td>
                <td v-if="childIndex === 0" :rowspan="item.children.length">{{ item.deptName }}</td>
                <td>{{ child.worker }}</td>
                <td>{{ child.orderQty }}</td>
                <td>{{ child.quantity }}</td>
              </tr>
            </template>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td>合计：</td>
              <td>{{ totalWorkorder }}</td>
              <td>{{ totalQuantity }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
import HeaderTitle from "src/components/HeaderTitle.vue";
import { ref, toRaw } from "vue";
import { useUserStore } from "src/stores/modules/userStore";
import { useReportStore } from "src/stores/modules/reportStore";
import { Loading, exportFile } from "quasar";
import { exportQCStockReport} from 'src/services/reportService'

import * as XLSX from 'xlsjs';
// params
const useUser = useUserStore();
const useReport = useReportStore();
let accID = null;
const dtrows = ref([]);
const strows = ref([]);
const rows = ref([]);
const totalOrder = ref(0);
const totalCount = ref(0);
const TableTotalData = ref([])
const totalWorkorder = ref(0);
const totalQuantity = ref(0);

function countQty(arr) {
  let count = 0;
  for (const item of arr) {
    count += item.quantity;
  }
  return count;
}
function exportToCSV() {
  // 准备CSV数据
  let csvContent = "data:text/csv;charset=utf-8,";

  // 添加表头
  csvContent += "检测员身份,检测员姓名,部门名称,工人姓名,单数,件数\n";

  // 添加数据行
  TableTotalData.value.forEach(item => {
    item.children.forEach(child => {
      csvContent += `${item.role_chinese_name},${item.cnName},${item.deptName},${child.worker},${child.orderQty},${child.quantity}\n`;
    });
  });
  csvContent += `,,,总数,${totalWorkorder.value},${totalQuantity.value}\n`;
  // 创建一个链接并触发下载
  const encodedUri = encodeURI(csvContent);
  const link = document.createElement("a");
  link.setAttribute("href", encodedUri);
  link.setAttribute("download", "实时存货报表-汇总.csv");
  document.body.appendChild(link); // 需要将链接元素添加到文档中才能触发点击
  link.click();
  document.body.removeChild(link); // 下载完成后移除链接元素
}
// init
const init = async () => {
  accID = useUser.currentDept.accID;
  console.log("accId: ", accID);
  // get handset
  const handset_res = await useReport.getQCInventory("handset", accID);
  console.log("handset_res: ", handset_res);
  if (handset_res) {
    dtrows.value = toRaw(
      useReport.realtime_handset.data.map((i) => {

        let count = i.checker.length - 1
        let workerArray = i.worker;
        let selectedWorker;

        // 取非空的最后一个或倒数第二个工人
        if (workerArray.length > 0) {
          let nonEmptyWorkers = workerArray.filter(worker => worker.department || worker.code || worker.name);
          if (nonEmptyWorkers.length > 0) {
            selectedWorker = nonEmptyWorkers[nonEmptyWorkers.length - 1];
          } else {
            selectedWorker = workerArray[workerArray.length - 1];
          }
        } else {
          selectedWorker = {};
        }
        console.log(selectedWorker)
        return {
          ...i,
          checker_code: i.checker[count].code,
          checker_name: i.checker[count].name,
          checker_role: i.checker[count].role,
          department: selectedWorker.department,
          worker_name: selectedWorker.name,
          worker_code: selectedWorker.code,
        };
      })
    );
    const groupedData = dtrows.value.reduce((result, obj) => {
      const { worker_name } = obj;
      if (!result[worker_name]) {
        result[worker_name] = [];
      }
      result[worker_name].push({
        quantity: obj.quantity,
      });
      return result;
    }, {});

    strows.value = { ...groupedData };


    for (let key in strows.value){
      const row = {
        'worker': key,
        'orderQty': strows.value[key].length,
        'quantity': countQty(strows.value[key]),
      }
      rows.value.push(row)
    }
    
    for (let worker in groupedData) {
      totalOrder.value += groupedData[worker].length;
      let totalQuantity = 0;
      groupedData[worker].forEach((obj) => {
        if (obj.quantity) {
          totalQuantity += obj.quantity;
        }
      });
      totalCount.value += totalQuantity;
    }
    TableTotalData.value = useReport.realtime_handset.group_by

    totalWorkorder.value = useReport.realtime_handset.summary.order_qty_count;
    totalQuantity.value = useReport.realtime_handset.summary.quantity_count;
  }
};
init();

// Function: Download Table as xlxs file
const genCsv = () => {
  console.log("downloading excel file... ");
  const cols = [
  {
    name: 'role',
    label: '检测员身份',
    field: 'role',
  },
  {
    name: 'checker',
    label: '检测员姓名',
    field: 'checker',
  },
  {
    name: 'dept',
    label: '部门名称',
    field: 'dept',
  },
  {
    name: 'worker',
    label: '工人姓名',
    field: 'worker',
  },
  {
    name: 'orderQty',
    label: '单数',
    field: 'orderQty',
  },  
  {
    name: 'quantity',
    label: '件数',
    field: 'quantity',
  }]
  const output = []

  let count = 0
  for (let row of rows.value){
    let role = ''
    let checker = ''
    let dept = ''
    if (count==0){
      role = useUser.currentDept.role_chinese_name
      checker = useUser.cnName
      dept = useUser.currentDept.deptName
    }
    const obj = {
      'role':role,
      'checker':checker,
      'dept':dept,
      'worker': row.worker,
      'orderQty': row.orderQty,
      'quantity': row.quantity,
    }
    output.push(obj)
    count++
  }

  const total = {
    'role':'',
    'checker':'',
    'dept':'',
    'worker': '合计：',
    'orderQty': totalOrder.value,
    'quantity': totalCount.value,
  }
  output.push(total)

  // const data_headers = header.forEach(({ v, position }) => {
  //   worksheet[position] =  {v} 
  // });

  const columnNames = ['检测员身份', '检测员姓名', '部门名称','工人姓名', '单数','件数'];
  
  // const header = columnNames.map((colName, index) => ({ v: colName, position: String.fromCharCode(65 + index) + '1' }));

  const tableData = output
  const worksheet = XLSX.utils.json_to_sheet(tableData);
  XLSX.utils.sheet_add_aoa(worksheet, [columnNames], { origin: "A1" });
// Add the column names to the worksheet
  
  const workbook = XLSX.utils.book_new();

  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

  const wbout = XLSX.write(workbook, {
    bookType: 'csv',
    type: 'array',
    bookSST: false,
    defaultEncoding: 'UTF-16LE'
  });

  
  const blob = new Blob([wbout], { type: 'application/octet-stream' });

  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = '实时存货报表-汇总.csv';
  link.click();
  URL.revokeObjectURL(link.href);

  // exportTable(cols,output,'实时存货报表-汇总')

};


const exportTable = async () => {
  console.log("downloading qc stock report... ");
  try {
    Loading.show()
    const res = await exportQCStockReport("handset", accID)
    // console.log(res.status)
    if (res.status==200){
      const filename = "QCstock.csv"
      // const filename = res.headers['content-disposition'].split('filename=')[1].replace(/"/g, '');

      const status = exportFile(filename, res.data, {
        encoding: 'utf-8',
        mimeType: 'text/csv;',
        byteOrderMark: '\uFEFF'
      })

      if (status!=true){
        $q.notify({
          message: '导出失败',
          color: 'negative',
          timeout: 2000,
          position: "center",
        })
      }else{
        $q.notify({
          message: '导出成功',
          color: 'positive',
          timeout: 2000,
          position: "center",
        })
      }

    }
  } catch (error) {
    console.log(error);
  }
  Loading.hide()
};


// Detail Table - Handset 明细
const dtcolumns = [
  {
    name: "serialNo",
    align: "center",
    label: "序号",
    field: "serialNo",
    sortable: false,
  },
  {
    name: "received_date",
    label: "收货日期",
    align: "center",
    field: (row) => row.received_date,
    format: (row) => {
      const a = row.split("T");
      return a[0];
    },
    sortable: true,
  },
  {
    name: "source",
    align: "center",
    label: "地点",
    field: "source",
    sortable: true,
  },
  {
    name: "workorder",
    align: "center",
    label: "生产单号",
    field: "workorder",
    sortable: true,
  },
  {
    name: "due_date",
    align: "center",
    label: "货单交货期",
    field: "due_date",
    format: (row) => {
      const a = row.split("T");
      return a[0];
    },
    sortable: true,
  },
  {
    name: "design",
    align: "center",
    label: "设计编号",
    field: "design",
    sortable: true,
  },
  {
    name: "gold_type",
    align: "center",
    label: "成色",
    field: "gold_type",
    sortable: true,
  },
  {
    name: "quantity",
    align: "center",
    label: "件数",
    field: "quantity",
    sortable: true,
  },
  {
    name: "department",
    align: "center",
    label: "部门名称",
    field: "department",
    sortable: true,
  },
  {
    name: "worker_code",
    align: "center",
    label: "工人编号",
    field: "worker_code",
    sortable: true,
  },
  {
    name: "worker_name",
    align: "center",
    label: "工人姓名",
    field: "worker_name",
    sortable: true,
  },
  {
    name: "checker_code",
    align: "center",
    label: "检测员编号",
    field: "checker_code",
    sortable: true,
  },
  {
    name: "checker_name",
    align: "center",
    label: "检测员姓名",
    field: "checker_name",
    sortable: true,
  },
  {
    name: "checker_role",
    align: "center",
    label: "检测员身份",
    field: "checker_role",
    sortable: true,
  },
];

// Summary Table - Transaction 汇总
const stcolumns = [
  {
    name: "serialNo",
    align: "center",
    label: "序号",
    field: "serialNo",
    sortable: false,
  },
  {
    name: "checkerRole",
    align: "center",
    label: "检测员身份",
    field: "checkerRole",
    sortable: false,
  },
  {
    name: "checkerName",
    align: "center",
    label: "检测员姓名",
    field: "checkerName",
    sortable: false,
  },
  {
    name: "dept",
    align: "center",
    label: "部门名称",
    field: "dept",
    sortable: false,
  },
  {
    name: "workerName",
    align: "center",
    label: "工人姓名",
    field: "workerName",
    sortable: false,
  },
  {
    name: "orderQty",
    align: "center",
    label: "单数",
    field: "orderQty",
    sortable: true,
  },
  { name: "qty", align: "center", label: "件数", field: "qty", sortable: true },
];
</script>

<style lang="scss">
.realtimeStockPage {
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 20px;
  font-size: 1rem;
  @media (max-width: 480px) {
    font-size: 1rem;
  }

  .detailsBox {
    width: 100%;
    background-color: rgba(255, 255, 255, 0.851);
    border-radius: 10px;
    margin-top: 10px;
    padding: 10px 10px 10px 10px;

    .dbTitle {
      color: #4436d0;
      font-weight: bold;
    }
    .titleHR {
      margin-left: 5px;
      border: 1px solid #4436d0;
    }
    .detailTbBox {
      margin-top: 10px;
      overflow: auto;
      width: 100%;
    }
  }
  .summaryBox {
    width: 100%;
    background-color: rgba(255, 255, 255, 0.851);
    border-radius: 10px;
    margin-top: 10px;
    padding: 10px 10px 10px 10px;

    .sbTitle {
      color: #4436d0;
      font-weight: bold;
    }
    .titleHR {
      margin-left: 5px;
      border: 1px solid #4436d0;
    }
    .summaryTbBox {
      overflow: auto;
      margin-top: 10px;
      width: 100%;
      .summaryTable {
        margin-top: 10px;
        width: 100%;
      }
    }
  }
  .exportBtnBox {
    margin-left: 10px;
    .exportBtn {
      font-size: 1rem;
      .exportSVG {
        margin-left: 5px;
      }
    }
  }
}
.my-table {
  padding: 0;
  border-collapse: collapse;
  text-align: center;
  font-size: 1rem;
  @media (max-width: 480px) {
    font-size: 1rem;
  }
  .my-table-header {
    height: 28px;
  }
}
.my-table,
.my-table td {
  padding: 4px 8px;
  border: solid 1px rgb(185, 184, 184);
}
</style>
